package com.baixiaowen.xiaoaointerview.并发基础篇;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Synchronized 锁使用
 *
 * @author Baixiaowen
 */
public class WaitAwait {

    public static void main(String[] args) throws InterruptedException {

        Lock lock = new ReentrantLock();
        Condition waitCond = lock.newCondition();

        Object obj = new Object();
        Thread t1 = new Thread(() -> {
            System.err.println("before-wait ...1");
            try {
                lock.lock();
//                synchronized (obj) {
//                    obj.wait();
//                }
                waitCond.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

            System.err.println("after-wait ...1");
        });

        Thread t2 = new Thread(() -> {
            System.err.println("before-wait ...2");
            try {
                lock.lock();
//                synchronized (obj) {
//                    obj.wait();
//                }
                waitCond.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.err.println("after-wait ...2");
        });

        t1.start();
        t2.start();

        Thread.sleep(1);
        lock.lock();
        waitCond.signalAll();
        lock.unlock();


//        synchronized (obj) {
//            obj.notifyAll();
//        }
    }

}
